package org.jeecg.modules.demo.upload.controller;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TestExcl {

    // 原始映射表
    private static final Map<String, String> HEIGHT_MAP = Map.of(
            "A", "小于5m", "B", "5m-10m", "C", "10m-15m", "D", "大于15m"
    );
    private static final Map<String, String> DISTANCE_MAP = Map.of(
            "A", "小于1m", "B", "1m-2m", "C", "2m-4m", "D", "大于4m"
    );
    private static final Map<String, String> SLOPE_MAP = Map.of(
            "A", "小于20°", "B", "20-30°", "C", "大于30°"
    );
    private static final Map<Integer, String> TYPE_MAP = Map.of(
            1, "岩质为主", 2, "岩质为主", 3, "岩土混合", 4, "土质为主", 5, "土质为主"
    );
    private static final Map<Integer, String> REVERSE_TYPE_MAP = Map.of(
            1, "A", 2, "A", 3, "B", 4, "C", 5, "C"
    );

    public static void main(String[] args) {
        String sourcePath = "E:\\项目资料\\项目资料\\边坡\\test1.xlsx";
        String outputPath = "E:\\项目资料\\项目资料\\边坡\\整治措施报表.xls";

        try {
            List<SlopeData> dataList = readSourceData(sourcePath);
            System.out.println("共读取数据：" + dataList.size() + " 条");
            writeToTarget(outputPath, dataList);
            System.out.println("数据整理完成！输出文件：" + new File(outputPath).getAbsolutePath());
        } catch (Exception e) {
            System.err.println("处理失败：" + e.getMessage());
            e.printStackTrace();
        }
    }

    /** 读取源文件数据并转换为 SlopeData 列表 */
    /**
     * 读取源文件数据并转换为 SlopeData 列表
     */
    private static List<SlopeData> readSourceData(String sourcePath) throws Exception {
        List<SlopeData> dataList = new ArrayList<>();
        // 支持中英文括号，提取类似 AAA-2-1 的编码格式
        Pattern pattern = Pattern.compile("[（(]([A-Z]{3}-\\d+-\\d+)[）)]");

        try (Workbook workbook = new XSSFWorkbook(new FileInputStream(sourcePath))) {
            Sheet sheet = workbook.getSheetAt(0); // 使用第一个 sheet

            for (Row row : sheet) {
                Cell cell = row.getCell(0); // 只读取第1列
                if (cell == null) continue;

                String content = getCellValue(cell);
                if (content.isEmpty()) continue;

                // 如果有多个措施，用换行符分割
                String[] measures = content.split("\n");
                for (String measure : measures) {
                    measure = measure.trim();
                    if (measure.isEmpty()) continue;

                    Matcher matcher = pattern.matcher(measure);
                    if (!matcher.find()) {
                        System.out.println("无法解析措施：" + measure);
                        continue;
                    }

                    String fullCode = matcher.group(1); // 得到 AAA-2-1
                    String[] parts = fullCode.split("-");
                    String codePart = parts[0]; // AAA
                    int typeNum = Integer.parseInt(parts[1]); // 2
                    int num = Integer.parseInt(parts[2]); // 1

                    String heightCode = codePart.substring(0, 1);
                    String distanceCode = codePart.substring(1, 2);
                    String slopeCode = codePart.substring(2, 3);

                    SlopeData data = new SlopeData();
                    data.height = HEIGHT_MAP.getOrDefault(heightCode, "未知");
                    data.distance = DISTANCE_MAP.getOrDefault(distanceCode, "未知");
                    data.slope = SLOPE_MAP.getOrDefault(slopeCode, "未知");
                    data.type = TYPE_MAP.getOrDefault(typeNum, "未知");
                    data.subType = typeNum;
                    data.num=num;
                    data.measure = measure; // 原始措施字符串

                    dataList.add(data);
                }
            }
        }
        return dataList;
    }
    /** 将整理后的数据写入新 Excel 文件 */
    private static void writeToTarget(String outputPath, List<SlopeData> dataList) throws Exception {
        try (Workbook workbook = new HSSFWorkbook();
             FileOutputStream fos = new FileOutputStream(outputPath)) {
            Sheet sheet = workbook.createSheet("整治措施");

            Row header1 = sheet.createRow(0);
            header1.createCell(0).setCellValue("整治措施报表");

            Row header2 = sheet.createRow(1);
            header2.createCell(0).setCellValue("导出人:管理员");

            Row headerRow = sheet.createRow(2);
            headerRow.createCell(0).setCellValue("切坡高");
            headerRow.createCell(1).setCellValue("坡墙距");
            headerRow.createCell(2).setCellValue("自然斜坡坡度");
            headerRow.createCell(3).setCellValue("切坡类型");
            headerRow.createCell(4).setCellValue("切坡子类型");
            headerRow.createCell(5).setCellValue("方案");
            headerRow.createCell(6).setCellValue("具体措施");
            headerRow.createCell(7).setCellValue("具体图集");

            int rowIndex = 3;
            for (SlopeData data : dataList) {
                Row row = sheet.createRow(rowIndex++);
                row.createCell(0).setCellValue(data.height);
                row.createCell(1).setCellValue(data.distance);
                row.createCell(2).setCellValue(data.slope);
                row.createCell(3).setCellValue(data.type);
                row.createCell(4).setCellValue(data.subType);
                row.createCell(5).setCellValue(data.num);
                row.createCell(6).setCellValue(data.measure);
                row.createCell(7).setCellValue(""); // 具体图集留空
            }

            workbook.write(fos);
        }
    }

    /** 安全获取单元格值 */
//    private static String getCellValue1(Cell cell) {
//        if (cell == null) return "";
//        return switch (cell.getCellType()) {
//            case STRING ->cell.getStringCellValue().trim();
//            case NUMERIC -> String.valueOf((int) cell.getNumericCellValue()).trim();
//            default -> "";
//        };
//    }
    private static String getCellValue(Cell cell) {
        if (cell == null) {
            return "";
        }
        if (cell.getCellType() == CellType.STRING) {
            return cell.getStringCellValue().trim();
        } else if (cell.getCellType() == CellType.NUMERIC) {
            return String.valueOf((int) cell.getNumericCellValue()).trim();
        } else {
            return "";
        }
    }

    /** 数据载体类 */
    static class SlopeData {
        String height;    // 切坡高（中文描述）
        String distance;  // 坡墙距（中文描述）
        String slope;     // 自然斜坡坡度（中文描述）
        String type;      // 切坡类型
        int subType;      // 切坡子类型（1~5）
        int num;      // 切坡子类型（1~5）
        String measure;   // 具体措施（完整字符串）
    }
}